<?php
namespace App\Http\Controllers\Home;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AnhourController extends Controller{
	// 倍投+5，每期投入



	// 5
	// 15
	// 35
	// 75
	// 155
	// 315
	// 635
	// 1275
	// 2555
	// 5115
	// 10235
	// 20475
	// 40955
	// 81915
	// 163835
	// 327675
	// 655355
	// 1310715

	//24小时1440期取部分期次投入与收益模拟（1个小时：720-780期次）
	public function index(){
		//清除数据
		DB::table('wlfd')->truncate();
		DB::table('bills')->truncate();

		$this->cAa();

		$d_id=DB::table('bills')->max('d_id');
		if($d_id){
			$d_id=$d_id+1;
			$this->uDin($d_id,720,780);
			$this->kj($d_id);
		}else{
			$this->uDin(1,720,780);
			$this->kj(1);
		}

		$money_inMax=DB::table('bills')->max('money_in');
		$money_inAll=DB::table('bills')->sum('money_in');
		$money_outAll=DB::table('bills')->sum('money_out');
		$data['money_inMax']=$money_inMax;
		$data['money_inAll']=$money_inAll;
		$data['money_outAll']=$money_outAll;
		$data['money_ins']=$money_outAll-$money_inAll;
		DB::table('money_in_an_hour')->insert($data);
		return ['投入最大'=>$money_inMax,'总投入'=>$money_inAll,'总收入'=>$money_outAll,'净收入'=>$data['money_ins']];
	}
	private function kj($d_id){
		$w_id=DB::table('bills')->where('d_id',$d_id)->max('w_id');
		$w_ids=DB::table('bills')->where('d_id',$d_id)->where('w_id',$w_id)->first();
		// 先开个奖
		if($w_ids){
			if($w_ids->state==0){
				$kres=DB::table('wlfd')->where('id',$w_ids->w_id)->first();
				$kj=$kres->one+$kres->two+$kres->three+$kres->four+$kres->five;
				if($kj>22){
					DB::table('bills')->where('id',$w_ids->id)->update(['state'=>1,'money_out'=>bcmul($w_ids->money_in,2,2)]);
				}else{
					DB::table('bills')->where('id',$w_ids->id)->update(['state'=>2,'money_out'=>0]);
				}
			}
		}
		
	}
	//u_id购买情况
	private function uDin($d_id,$now,$n){

		$now++;

		$this->kj($d_id);

		//投
		$data['u_id']=1;
		$data['d_id']=$d_id;
		$w_id=DB::table('bills')->where('u_id',$data['u_id'])->where('d_id',$data['d_id'])->max('w_id');
		if($w_id){
			$data['w_id']=$w_id+1;
		}else{
			$data['w_id']=720+1;
		}
		$data['state']=0;
		$w_ids=DB::table('bills')->where('u_id',$data['u_id'])->where('d_id',$data['d_id'])->where('w_id',$w_id)->first();
		if($w_ids){
			if($w_ids->state==1){//若上期中奖、初始金额投入
				$data['money_in']=5;
			}elseif($w_ids->state==2){//若上期未中奖、上期金额加倍+5投入
				$data['money_in']=bcadd(bcmul($w_ids->money_in,2,2),5,2);
			}else{//当天第一期
				$data['money_in']=5;
			}
		}else{//第一期
			$data['money_in']=5;
		}
		
		$data['money_out']=0;
		
		DB::table('bills')->insertGetId($data);
		if($now<$n){
			$this->uDin($d_id,$now,$n);
		}else{
			return;
		}
	}
	//添加数据
	private function cAa(){
		$i=0;
		while ( $i < 1440) {
			$data['one']=mt_rand(0,9);
			$data['two']=mt_rand(0,9);
			$data['three']=mt_rand(0,9);
			$data['four']=mt_rand(0,9);
			$data['five']=mt_rand(0,9);
			$data['time']=time();
			DB::table('wlfd')->insert($data);
			$i++;
		}
	}
}